package com.itheima.reggie.contorller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody Map<String, String> map, HttpSession session) {
        String phone = map.get("phone");
        //1. 随机生成验证码
  String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //String code = "8888";
        log.info("发送验证码 phone:{}, 生成code:{}", phone, code);
        //2. 发送短信
//        SMSUtils.sendMessage("ABC商城", "SMS_205884038", phone, code);
        //3. 将验证码存入session，key：phone，value：验证码
       // session.setAttribute(phone, code);
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        return R.success("短信验证码已发送");
    }

    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map, HttpSession session) {
        log.info("用户登陆请求 map:{}", map);
        //1. 比对用户请求的验证码和session中的验证码是否一致
        //如果不一致，返回登陆失败
        //获取前端传入的手机号和验证码
        String phone = map.get("phone");
        String code = map.get("code");

        //获取session中的code
        //String codeInSession = (String) session.getAttribute(phone);
        Object codeInSession = redisTemplate.opsForValue().get(phone);
        if(codeInSession == null || !codeInSession.equals(code)){
            //验证码不一致，返回失败
            return R.error("验证码错误");
        }
        //2. 判断用户是否存在，如果不存在，注册新用户
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, phone);
        User user = userService.getOne(lqw);
        if(user == null) {
            //用户不存在，注册新用户
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        } else{
            //3. 如果用户存在，判断是否禁用，如果已经禁用，登陆失败
            Integer status = user.getStatus();
            if(status == 0) {
                //用户已禁用，不允许登陆
                return R.error("用户已禁用");
            }
        }
        //4. 登陆成功将用户的id存入session
        session.setAttribute("user", user.getId());
        redisTemplate.delete(phone);
        return R.success(user);
    }
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("GoodBye,小伙子");
    }
}